/**
 * Copyright (C) 2010 Sergey Grigoriev <s.a.grigoriev@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.gmf.core

import org.apache.log4j.Logger
import org.apache.maven.project.MavenProject
import org.apache.commons.io.FileUtils
import org.apache.maven.plugin.MojoExecutionException
import com.google.inject.Injector
import com.google.inject.Inject

/**
 * Provides access to Flex SDK commands
 */
class FlexSdkFacade {

  @Inject
  Logger l4j

  def flexSdkVersion

  def flexSdkBuild

  def private flexSdkHome = "flex SDK home is not defined"

  Injector injector

  def synchronized getFlexSdkHome() {
    return flexSdkHome
  }

  def synchronized setFlexSdkHome(newVal) {
    if (newVal != flexSdkHome) {
      detectFlexSdkVersion(newVal)
    }
    flexSdkHome = newVal
  }

  def createCommand(name, MavenProject project) {
    def result = new OSCommand(name, project.basedir, [flexSdkHome, 'bin'].join(File.separator))
    injector.injectMembers(result)
    result
  }

  private void detectFlexSdkVersion(newFlexSdkHome) {

    if (!newFlexSdkHome || !new File(newFlexSdkHome)) {
      throw new MojoExecutionException("Folder with Flex SDK  ${newFlexSdkHome} doesn't exist")
    }

    OSCommand cmd = new OSCommand('mxmlc', new File('.'), [newFlexSdkHome, 'bin'].join(File.separator))
    injector.injectMembers(cmd)
    cmd << ['-version']
    cmd.run()
    def pattern = ~/[^ ]+ +([^ ]+) +[^ ]+ +([^ ]+)$/
    def matcher = pattern.matcher(cmd.stdout)
    if (!matcher.matches()) {
      throw new IllegalStateException('Could not detect flexSdkVersion invoking mxmlc -version')
    }
    flexSdkVersion = matcher.group(1)
    flexSdkBuild = matcher.group(2)
    l4j.info "Inspecting ${newFlexSdkHome} ..."
    l4j.info "Detected Flex SDK version ${flexSdkVersion} build ${flexSdkBuild}"
  }

  /**
   * Copies framework RSL to the specified folder
   * @param to Destination folder
   */
  void copyFrameworkRsls(String to) {
    new File([flexSdkHome, 'frameworks', 'rsls'].join(File.separator)).eachFile {
      FileUtils.copyFileToDirectory(it, new File(to))
    }
  }
}
